<template>
	<view>
		<nav-bar title="衷依慧店" :showLeftIcon="false"></nav-bar>
		<search placeholder="搜索技师" :leftSlot="true" @search="search" @searchFocus="searchFocus">
			<template #leftSlot>
				<view class="city" @click="toCity">
					<uni-icons type="location" size="20" color="#fff"></uni-icons>
					<view style="margin: 0 10rpx;">{{ city }}</view>
					<uni-icons type="bottom" size="12" color="#fff"></uni-icons>
				</view>
			</template>
		</search>
		<view class="contain">
			<view class="common-title">
				<view class="box-line"></view>
				<view class="text">请选择技师</view>
			</view>
			<you-scroll :loadingHeight="loadingHeight" :mainHeight="mainHeight" :isRequestSuccess="isRequestSuccess"
				@onRefresh="onRefresh">
				<template>
					<view v-if="isLoading" class="common-loading">
						<image class="loading-img" :src="baseIconUrl + 'icon_loading.png'" />
					</view>
					<technician-list v-else-if="technicianList && technicianList.length"
						:technicianList="technicianList" @reserve="clickReserve"
						@toDetail="clickToDetail"></technician-list>
					<view v-else class="common-no-data">
						<image class="no-data-img" :src="baseImgUrl + 'img_no_project.png'" alt="" />
						<view class="text">暂无技师</view>
					</view>
					<u-datetime-picker ref="datetimePicker" :show="show1" v-model="value4" mode="datetime"
						@confirm="confirm1" @cancel="show1=false" :formatter="formatter"
						:visibleItemCount="9"></u-datetime-picker>
				</template>
			</you-scroll>
		</view>
		<u-picker :show="show" :columns="columns" title="选择城市" confirmColor="rgba(194, 126, 21, 1)"
			:closeOnClickOverlay="true" @confirm="confirm" @cancel="cancel"></u-picker>
	</view>
</template>

<script>
	import YouPopup from '@/components/you-popup/index.vue'
	import NavBar from "@/components/nav-bar"
	import Search from '@/components/search/index'
	import YouScroll from '@/components/you-scroll/index'
	import api_technician from '@/api/technician.js'
	import TechnicianList from '@/subPages/components/technicianList'
	import pageConfig from '@/config'
	import shopList from "@/subPages/components/shopList"
	import api_common from '@/api/common'
	import store from '../../store'
	export default {
		name: "index",
		components: {
			NavBar,
			Search,
			YouPopup,
			YouScroll,
			TechnicianList,
			shopList
		},
		data() {
			return {
				baseImgUrl: pageConfig.baseImgUrl,
				baseIconUrl: pageConfig.baseIconUrl,
				mainHeight: '',
				loadingHeight: '',
				show1: false,
				value4: Number(new Date()),
				technicianList: [],
				isLoading: false,
				transferData: {},
				show: false,
				columns: [
					['中国', '美国', '日本']
				],
				cityList: [],
				isRequestSuccess: false
			}
		},
		onLoad() {
			this.mainHeight = this.$store.getters.heightData.mainSearchHeight.split('px')[0] - 76 + 'px'
			this.loadingHeight = this.$store.getters.heightData.mainSearchHeight.split('px')[0] - 96 + 'px'
			this.getLocation()
		},
		mounted() {
			uni.$on('city', (data) => {
				const list = this.cityList.filter((item) => {
					return item.shortName === data.city
				})
				store.commit('CITY_NAME', list[0].cityName)
				store.commit('CITY_DATA', {
					latitude: list[0].latitude,
					longitude: list[0].longitude,
					cityString: this.$store.getters.cityName
				})
				this.getTechnicianList()
			})
		},
		computed: {
			city() {
				return this.$store.getters.cityName
			}
		},
		methods: {
			getTechnicianList() {
				this.isLoading = true
				const params = {
					minProIsShow: 1,
					...this.$store.getters.cityData,
					state: 1
				}
				api_technician.fetchTechnicianList(params).then(res => {
					this.isLoading = false
					if (res.data.length > 0) {
						this.technicianList = res.data
					} else {
						this.technicianList = []
					}
					this.isRequestSuccess = true
				}).catch(err => {
					this.isLoading = false
				})
			},
			clickToDetail(item) {
				uni.navigateTo({
					url: `/subPages/technician/technicianDetail?id=${item.technician.id}`,
				})
			},
			// 下拉刷新
			onRefresh() {
				this.technicianList = []
				this.isRequestSuccess = false
				this.getTechnicianList()
			},
			clickReserve(item) {
				// this.show1 = true
				const transferData = {
					id: item.technician.id,
					name: item.technician.name,
					avatar: item.technician.avatar,
					score: item.score,
					regionId: item.technician.belongAreaId,
					storeId: item.technician.belongStoreId,
					storeName: item.technician.belongStoreName,
					synopsis: item.technician.synopsis
				}
				this.transferData = transferData
				const params = encodeURIComponent(JSON.stringify(transferData))
				// uni.navigateTo({
				//   url:  `/subPages/technician/reserveTime?transferData=${params}`
				// })
				uni.navigateTo({
					url: `/subPages/technician/chooseProject?transferData=${params}`
				})
			},
			confirm1(e) {
				// 获取年、月、日、时、分、秒
				// 使用 Date 对象将时间戳转换为可读的日期和时间格式
				var date = new Date(this.value4);

				// 获取年、月、日、时、分
				var year = date.getFullYear();
				var month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份从 0 开始，需加一并补零
				var day = ('0' + date.getDate()).slice(-2); // 补零
				var hours = ('0' + date.getHours()).slice(-2); // 补零
				var minutes = date.getMinutes();

				// 根据分钟数的范围设置不同的值
				if (minutes >= 0 && minutes <= 10) {
					minutes = 10;
				} else if (minutes >= 11 && minutes <= 20) {
					minutes = 20;
				} else if (minutes >= 21 && minutes <= 30) {
					minutes = 30;
				} else if (minutes >= 31 && minutes <= 40) {
					minutes = 40;
				} else if (minutes >= 41 && minutes <= 50) {
					minutes = 50;
				} else {
					minutes = 0;
					hours = ('0' + (parseInt(hours) + 1)).slice(-2); // 小时加一，并补零
				}

				// 格式化日期和时间字符串
				var formattedDate = year + '/' + month + '/' + day;
				var formattedTime = hours + ':' + ('0' + minutes).slice(-2); // 补零

				// 将格式化后的日期和时间存储在相应的字段中
				var reserveDate = formattedDate;
				var reserveTime = formattedTime;

				// 将格式化后的日期和时间存储在相应的字段中
				var reserveDate = formattedDate;
				var reserveTime = formattedTime;

				const transferData = {
					...this.transferData,
					reserveDate: reserveDate,
					reserveTime: reserveTime
				}
				const params = encodeURIComponent(JSON.stringify(transferData))
				uni.navigateTo({
					url: `/subPages/technician/chooseProject?transferData=${params}`
				})
				this.show1 = false
			},
			getAllCity() {
				api_common.fetchAllCity().then((res) => {
					this.cityList = res.data
				})
			},
			confirm(e) {
				console.log('lll', e)
			},
			cancel() {
				this.show = false
			},
			toDetail(item) {
				uni.navigateTo({
					url: '/subPages/home/shopDetail'
				})
			},

			submitClick(item) {
				uni.navigateTo({
					url: '/subPages/technician/reserveTime'
				})
			},
			async search(value) {
				const params = {
					technicianName: value,
					minProIsShow: 1,
					...this.$store.getters.cityData,
					state: 1
				}
				const res = await api_technician.fetchTechnicianList(params)
				console.log('搜索',res)
				if (res.code == 200) {
					this.technicianList = res.data
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
				}
			},
			searchFocus(value) {
				// const params = encodeURIComponent(JSON.stringify(this.$store.getters.cityData));
				// uni.navigateTo({
				// 	url: `/subPages/technician/technicianSearch?params=${params}`,
				// })
				this.search(value)
			},
			toCity() {
				uni.navigateTo({
					url: '/subPages/home/city',
				})
			},
			getLocation() {
				uni.getLocation({
					provider: 'system',
					success: (res) => {
						store.commit('CITY_DATA', {
							latitude: res.latitude,
							longitude: res.longitude
						})
					}
				})
				uni.getLocation({
					type: 'gcj02',
					success: res => {
						const latitude = res.latitude.toFixed(6);
						const longitude = res.longitude.toFixed(6);
						this.latitude = latitude;
						this.longitude = longitude;
						this.reverseGeocode(res.longitude, res.latitude);
					},
					fail: err => {
						console.log('定位失败:', err);
					}
				})
			},
			reverseGeocode(longitude, latitude) {
				uni.request({
					method: 'get',
					url: 'https://restapi.amap.com/v3/geocode/regeo',
					data: {
						key: '6b9fb008bdd4abde0a32433a82ff06cd',
						location: `${longitude},${latitude}`,
						extensions: 'base',
						output: 'json',
					},
					success: (res) => {
						if (res.data.status === '1') {
							if (res.data.regeocode && res.data.regeocode.formatted_address) {
								const address = res.data.regeocode.addressComponent.city;
								store.commit('CITY_NAME', address)
								store.commit('CITY_DATA', {
									...this.$store.getters.cityData,
									cityString: this.$store.getters.cityName
								})
								this.getTechnicianList()
								this.getAllCity()
							} else {
								console.error('无法获取地址信息');
							}
						} else {
							console.error('逆地理编码请求失败');
						}
					},
					fail: (err) => {
						console.error(err);
					}
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.popup-contain {
		width: 100%;
	}

	.cancel {
		width: 130rpx;
		height: 49rpx;
		border-radius: 38rpx 38rpx 38rpx 38rpx;
		opacity: 1;
		border: 1rpx solid #C27E15;
		line-height: 49rpx;
		text-align: center;
		font-size: 24rpx;
		font-weight: 400;
		color: #C27E15;
	}

	.city {
		color: rgba(255, 255, 255, 1);
		display: flex;
		margin-right: 20rpx;
		transform: translateY(15rpx);
	}

	.contain {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		width: 100%;
		margin-top: 16px;
	}
</style>